<?php
declare (strict_types = 1);

namespace app\api\model;

use app\admin\model\Store;
use think\Model;

/**
 * @mixin \think\Model
 */
class CarBindStore extends Model
{
    //
    /**
     * 根据用户id获取门店列表
     * @param $user_id
     * @return array|bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getStoreByUserId($user_id,$car_id=0){
        $where = [];
        if(!empty($car_id)){
            $where['car_id'] = $car_id;
        }else{
            $where['user_id'] = $user_id;
        }
            $data = $this->alias('cbs')->join('store s','cbs.store_id=s.id','left')->where($where)->select();
            if(!empty($data)){
                $list = $data->toArray();
                foreach ($list as  $key=>$val){
                    $recharge = UserMerchantRecharge::where(['user_id'=>$val['user_id'],'manager_id'=>$val['manager_id']])->find();
                    $list[$key]['balance'] = $recharge->price??0;
                    $data = ['manager_id'=>$val['manager_id']];
                    $num = Store::where($data)->count('id');
                    $list[$key]['chain'] = $num? $num:0;
                }
                return $list;
            }
            return $data;
    }

    /**
     * 车辆绑定门店
     * @param $data
     * @return CarBindStore|Model
     */
    public static function addData($data){
        $result = self::create($data);
        return $result;
    }
}
